package com.mjoys.util;

import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;
//import org.apache.commons.lang.ArrayUtils;
//import org.apache.commons.validator.routines.EmailValidator;

public class StringUtil {
//	private static final EmailValidator emailValidator = EmailValidator.getInstance();
//
//	public static String arrayToStr(Integer[] arrayInt){
//		String str = "";
//		if(arrayInt!=null){
//			String _str = ArrayUtils.toString(arrayInt);
//			str = _str.substring(1, _str.length()-1);
//		}
//		return str;
//	}
	
	public static Integer[] strToArray(String str,String regex){
		Integer[] arrayInt = null;
		if(str!=null){
			String[] strArray = str.split(regex);
			if(strArray!=null&&strArray.length>0){
				arrayInt = new Integer[strArray.length];
				for(int i=0;i<strArray.length;i++){
					String string = strArray[i];
					arrayInt[i] = Integer.parseInt(string);
				}
			}
		}
		return arrayInt;
	}

	/**
	 * url编码
	 * 
	 * @param str
	 * @return
	 */
	public static String urlencoder(String str) {
		return urlencoder(str, "UTF-8");
	}
	
	/**
	 * url编码
	 * 
	 * @param str
	 * @param charsetName
	 * @return
	 */
	public static String urlencoder(String str, String charsetName) {
		if (str == null || str == "")
			return "";
		try {
			return URLEncoder.encode(str, charsetName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * url解码，这个现在用于ajax
	 * 
	 * @param str
	 * @return
	 */
	public static String urldecoder(String str) {
		return urldecoder(str, "UTF-8");
	}

	/**
	 * url解码
	 * 
	 * @param str
	 * @param charsetName
	 * @return
	 */
	public static String urldecoder(String str, String charsetName) {
		if (str == null || str == "")
			return "";
		try {
			return URLDecoder.decode(str, charsetName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 转换为script可用的安全字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String toScriptStr(String str) {
		if (StringUtil.isEmpty(str))
			return "";
		str = str.replace("\\", "\\\\").replace("\n", "\\n").replace("\"", "\\\"").replaceAll("	", " ").replaceAll("  ", " ").replace("\r", "");
		return str;
	}

	/**
	 * 截取字符串
	 * 
	 * @param content
	 * @param length
	 * @return
	 */
	public static String showShort(String content, int length, String mark) {
		if (content == null)
			return null;
		if (content.getBytes().length <= length)
			return content;

		byte[] s = content.getBytes();
		int flag = 0;
		for (int i = 0; i < length; ++i) {
			if (s[i] < 0)
				flag++;
		}
		if (flag % 2 != 0)
			length--;

		byte[] d = new byte[length];
		System.arraycopy(s, 0, d, 0, length);
		return new String(d) + mark;
	}

	public static String showShort(String content, int length) {
		return showShort(content, length, "..");
	}

	/**
	 * 转换为html代码
	 * 
	 * @param str
	 * @return
	 */
	public static String toHtml(String str) {
		String temp = str;
		temp = temp.replaceAll(" ", "&nbsp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<br />").replaceAll("\r", "");
		return temp;
	}

	/**
	 * 编码BASE64值
	 * 
	 * @param s
	 * @return
	 */
	public static String encodeBASE64(String s) {
		if (s == null)
			return null;
		return new String(Base64.encodeBase64(s.getBytes()));
	}

	/**
	 * 解码BASE64值
	 * 
	 * @param s
	 * @return
	 */
	public static String decodeBASE64(String s) {
		if (s == null)
			return null;
		return new String(Base64.decodeBase64(s.getBytes()));
	}

	/**
	 * 得到md5值
	 * 
	 * @param str
	 * @return
	 */
	public static String getMD5(String str) {
		if (str == null || str.length() == 0) {
			return "";
		}

		StringBuffer hexString = new StringBuffer();

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte[] hash = md.digest();

			for (int i = 0; i < hash.length; i++) {
				if ((0xff & hash[i]) < 0x10) {
					hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
				} else {
					hexString.append(Integer.toHexString(0xFF & hash[i]));
				}
			}
		} catch (NoSuchAlgorithmException e) {

		}
		return hexString.toString();
	}

	public static String get16Md5(String plainText) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
//			System.out.println("result: " + buf.toString());// 32位的加密
			return buf.toString().substring(8, 24);// 16位的加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 连接数组
	 * 
	 * @param arr
	 * @param type
	 * @return
	 */
	public static String joinArr(Object[] arr, String type) {
		if (arr == null)
			return "";
		StringBuilder tmp = new StringBuilder();
		int i = 0;
		for (Object o : arr) {
			String s = String.valueOf(o);
			if (i > 0) {
				tmp.append(type);
			}
			tmp.append(s);
			i++;
		}
		return tmp.toString();
	}

	/**
	 * 连接数组
	 * 
	 * @param arr
	 * @param type
	 * @param out
	 * @return
	 */
	public static String joinArrforInt(int[] arr, String type, int out) {
		if (arr == null)
			return "";
		StringBuilder tmp = new StringBuilder();
		int i = 0;
		for (int o : arr) {
			if (o == out)
				continue;
			if (i > 0) {
				tmp.append(type);
			}
			tmp.append(String.valueOf(o));
			i++;
		}
		return tmp.toString();
	}

	public static String joinArrforSerializable(Serializable[] arr, String type) {
		if (arr == null)
			return "";
		StringBuilder tmp = new StringBuilder();
		int i = 0;
		for (Serializable o : arr) {
			if (o == null)
				continue;
			if (i > 0) {
				tmp.append(type);
			}
			tmp.append(String.valueOf(o));
			i++;
		}
		return tmp.toString();
	}

	/**
	 * 查找数据中的值
	 * 
	 * @param index
	 * @param strarr
	 * @param type
	 * @return
	 */
	public static boolean findArr(String index, String strarr, String type) {
		if (StringUtil.isEmpty(strarr))
			return false;
		String[] l = strarr.split(type);
		for (int i = 0; i < l.length; i++) {
			if (l[i].equals(index)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 查找数据中的值
	 * 
	 * @param index
	 * @param strarr
	 * @param type
	 * @return
	 */
	public static int indexArr(String index, String strarr, String type) {
		if (StringUtil.isEmpty(strarr))
			return -1;
		String[] l = strarr.split(type);
		for (int i = 0; i < l.length; i++) {
			if (l[i].equals(index)) {
				return i;
			}
		}
		return -1;
	}

	/**
	 * 删除数据中的值
	 * 
	 * @param index
	 * @param strarr
	 * @param type
	 * @return
	 */
	public static String delArr(String index, String strarr, String type) {
		if (StringUtil.isEmpty(strarr))
			return "";
		String[] l = strarr.split(type);
		StringBuilder tmp = new StringBuilder();
		for (int i = 0; i < l.length; i++) {
			if (!l[i].equals(index) && l[i].length() > 0) {
				if (tmp.length() > 0)
					tmp.append(type);
				tmp.append(l[i]);
			}
		}
		return tmp.toString();
	}

	/**
	 * 连接字符串
	 * 
	 * @param str
	 * @param type
	 * @return
	 */
	public static String joinString(String[] str, String type) {
		StringBuilder s = new StringBuilder();
		int i = 0;
		for (String value : str) {
			if (i > 0 && !StringUtil.isEmpty(type))
				s.append(type);
			s.append(value);
			i++;
		}
		return s.toString();
	}

	/**
	 * 得到安全url
	 * 
	 * @param url
	 * @return
	 */
	public static String setSafeUrl(String url) {
		if (url.indexOf("?") >= 0) {
			url += "&";
		} else {
			url += "?";
		}
		return url;
	}

	/**
	 * 转换为安全字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String toSafeStr(String str) {
		if (str == null)
			return "";
		str = str.replaceAll("\"", "＂").replaceAll("'", "＇").replaceAll("	", " ").replaceAll("  ", " ").replaceAll("\r", "").replaceAll("\n", "\\n");
		return str;
	}

	public static String delNullStr(String str) {
		if (str == null)
			return "";
		return str;
	}

	public static String utf2gbk(String str) {
		String tmp = "";
		try {
			tmp = new String(str.getBytes("utf-8"), "gbk");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return tmp;
	}

	public static String gbk2utf(String str) {
		String tmp = "";
		try {
			tmp = new String(str.getBytes("gbk"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return tmp;
	}

	/**
	 * 解码QuotedPrintable字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String decodeQuotedPrintable(String str) {
		byte ESCAPE_CHAR = '=';
		if (str == null) {
			return null;
		}
		byte[] bytes = str.getBytes();
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		for (int i = 0; i < bytes.length; i++) {
			int b = bytes[i];
			if (b == ESCAPE_CHAR) {
				try {
					int u = Character.digit((char) bytes[++i], 16);
					int l = Character.digit((char) bytes[++i], 16);
					if (u == -1 || l == -1) {
						// 出错
						return "";
					}
					buffer.write((char) ((u << 4) + l));
				} catch (ArrayIndexOutOfBoundsException e) {
					// 出错
					return "";
				}
			} else {
				buffer.write(b);
			}
		}
		bytes = buffer.toByteArray();
		str = "";
		try {
			str = new String(bytes, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		if (str == null)
			return true;
		if (str.length() == 0)
			return true;
		return false;
	}

	/**
	 * 是否不为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(String str) {
		if (str != null) {
			if (str.length() == 0) {
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	/**
	 * 是email
	 * 
	 * @param str
	 * @return
	 */
//	public static boolean isEmail(String str) {
//		return emailValidator.isValid(str);
//	}

	/**
	 * bytes 到 chars
	 * 
	 * @param bytes
	 * @param offset
	 * @param length
	 * @return
	 */
	public static char[] bytesToChars(byte[] bytes, int offset, int length) {
		String s = new String(bytes, offset, length);
		char chars[] = s.toCharArray();
		return chars;
	}

	/**
	 * 截取字符串
	 * 
	 * @param source
	 * @param start
	 * @param end
	 * @return
	 */
	public static String findStr(String source, String start, String end) {
		if (source == null)
			return null;
		int i = 0;
		if (!isEmpty(start)) {
			i = source.indexOf(start);
			if (i < 0)
				return null;
			source = source.substring(i + start.length());
		}
		if (!isEmpty(end)) {
			i = source.indexOf(end);
			if (i < 0)
				return null;
			source = source.substring(0, i);
		}
		return source;
	}

	/**
	 * 用0补全数值
	 * 
	 * @param sDatesBefor
	 * @param length
	 * @return
	 */
	public static String getIndexString(int index, int length) {
		String sDatesBefor = String.valueOf(index);
		while (sDatesBefor.length() < length) {
			sDatesBefor = "0" + sDatesBefor;
		}
		return sDatesBefor;
	}

	/**
	 * 得到用0补全数值的路径
	 * 
	 * @param index
	 * @param length
	 * @return
	 */
	public static String getIndexPath(int index, int length) {
		StringBuffer tmp = new StringBuffer();
		String idstr = getIndexString(index, length);
		for (int i = 0; i < idstr.length(); i += 2) {
			tmp.append("/" + idstr.substring(i, i + 2));
		}
		return tmp.toString();
	}

	/**
	 * email结尾
	 * 
	 * @param email
	 * @return
	 */
	public static String getEmailExt(String email) {
		return email.substring(email.indexOf("@") + 1);
	}

	/**
	 * email名
	 * 
	 * @param email
	 * @return
	 */
	public static String getEmailName(String email) {
		return email.substring(0, email.indexOf("@"));
	}

	/**
	 * 首字母小写,只能用英文
	 * 
	 * @param str
	 * @return
	 */
	public static String getFrist2LowerCase(String str) {
		return str.substring(0, 1).toLowerCase() + str.substring(1);
	}
	
	public static String replaceEmpty(String str){
		if(str != null && str.length()>0){
			return str.replaceAll("\\s*", "");
		}
		return str ;
	}
	
	
	public static String unescape(String src) { 
		if(StringUtil.isEmpty(src)) return src;
        StringBuffer tmp = new StringBuffer();  
        tmp.ensureCapacity(src.length());  
        int lastPos = 0, pos = 0;  
        char ch;  
        while (lastPos < src.length()) {  
            pos = src.indexOf("%", lastPos);  
            if (pos == lastPos) {  
                if (src.charAt(pos + 1) == 'u') {  
                    ch = (char) Integer.parseInt(src  
                            .substring(pos + 2, pos + 6), 16);  
                    tmp.append(ch);  
                    lastPos = pos + 6;  
                } else {  
                    ch = (char) Integer.parseInt(src  
                            .substring(pos + 1, pos + 3), 16);  
                    tmp.append(ch);  
                    lastPos = pos + 3;  
                }  
            } else {  
                if (pos == -1) {  
                    tmp.append(src.substring(lastPos));  
                    lastPos = src.length();  
                } else {  
                    tmp.append(src.substring(lastPos, pos));  
                    lastPos = pos;  
                }  
            }  
        }  
        return tmp.toString();  
    }

	public static String escape(String src) {
		if(StringUtil.isEmpty(src)) return "";
		int i;  
        char j;  
        StringBuffer tmp = new StringBuffer();  
        tmp.ensureCapacity(src.length() * 6);  
        for (i = 0; i < src.length(); i++) {  
            j = src.charAt(i);  
            if (Character.isDigit(j) || Character.isLowerCase(j)  
                    || Character.isUpperCase(j))  
                tmp.append(j);  
            else if (j < 256) {  
                tmp.append("%");  
                if (j < 16)  
                    tmp.append("0");  
                tmp.append(Integer.toString(j, 16));  
            } else {  
                tmp.append("%u");  
                tmp.append(Integer.toString(j, 16));  
            }  
        }  
        return tmp.toString();  
	}  
	
	public static void main(String[] args) {
//		&m34nh4fd22
		System.out.println(StringUtil.getMD5("mjoys"+"&m34nh4fd22"+"888888"));
	}
	
}